<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"> 
        <title>栈的封装</title>
    </head>
    <body>
        <script>
            //Method:和某一个对象实例有联系
            //function
            //封装栈类
            function Stack(){

                this.items = [];

               //1.将元素压入栈
                Stack.prototype.push = function (element){
                    this.items.push(element);
                }

                //2.从栈中取出元素
                Stack.prototype.pop = function (){
                    return this.items.pop();
                }

                //3.查看栈顶元素
                Stack.prototype.peek = function () {
                    return this.items[this.items.length - 1];
                }

                //4.判断栈是否为空
                Stack.prototype.isEmpty = function () {
                    return this.items.length == 0;
                }

                //5.获取栈中元素的个数
                Stack.prototype.size = function (){
                    return this.items.length;
                }

                //6.toString方法
                Stack.prototype.toString = function (){
                   var resultString = '';
                   for(let i = 0; i< this.items.length; i++){
                       resultString += this.items[i] +' '
                   }
                   return resultString;
                }

            }

            var s = new Stack();
            s.push(1);
            console.log(s);
            // s.push(2);
            // s.push(3);
            // s.push(4);
            // alert(s);
            // s.pop();
            // s.pop();
            // alert(s.peek());
            // alert(s.isEmpty());
            // alert(s.size());

            //函数：将十进制转成二进制
            function dec2bin(decNumber){
                //1.定义栈对象
                var stack = new Stack();

                //2.循环操作
                while(decNumber>0){
                    stack.push(decNumber%2);
                    decNumber=Math.floor(decNumber/2);
                }
                var str="";

                while(!stack.isEmpty()){
                    str += stack.pop();
                }
                return str;
            }
                
            alert(dec2bin(100));


        </script>
    </body>
</html>